<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">用户管理</h2>
      <button @click="showCreateDialog = true" class="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
        <PlusIcon class="h-5 w-5 mr-2" />
        新增用户
      </button>
    </div>

    <!-- 搜索筛选 -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label for="searchUsername" class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
          <input type="text" id="searchUsername" v-model="searchForm.username" placeholder="请输入用户名" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div>
          <label for="searchRole" class="block text-sm font-medium text-gray-700 mb-2">角色</label>
          <select id="searchRole" v-model="searchForm.role" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">全部角色</option>
            <option value="ADMIN">系统管理员</option>
            <option value="LEADER">上级领导</option>
            <option value="LAB_MANAGER">实验室管理员</option>
          </select>
        </div>
        <div>
          <label for="searchLaboratory" class="block text-sm font-medium text-gray-700 mb-2">实验室</label>
          <select id="searchLaboratory" v-model="searchForm.laboratory" class="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">全部实验室</option>
            <option value="计算机实验室A">计算机实验室A</option>
            <option value="计算机实验室B">计算机实验室B</option>
            <option value="化学实验室">化学实验室</option>
            <option value="生物实验室">生物实验室</option>
            <option value="物理实验室">物理实验室</option>
          </select>
        </div>
        <div class="flex items-end space-x-2">
          <button @click="handleSearch" class="flex-1 px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
            搜索
          </button>
          <button @click="handleReset" class="flex-1 px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
            重置
          </button>
        </div>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="bg-white rounded-xl shadow-lg overflow-hidden">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">角色</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">实验室</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="user in users" :key="user.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div class="flex-shrink-0 h-10 w-10">
                    <div class="h-10 w-10 rounded-full bg-indigo-100 flex items-center justify-center">
                      <UserIcon class="h-6 w-6 text-indigo-600" />
                    </div>
                  </div>
                  <div class="ml-4">
                    <div class="text-sm font-medium text-gray-900">{{ user.username }}</div>
                    <div class="text-sm text-gray-500">{{ user.email || '未设置邮箱' }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getRoleBadgeClass(user.role)" class="inline-flex px-2 py-1 text-xs font-semibold rounded-full">
                  {{ getRoleText(user.role) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                {{ user.laboratoryName || '未分配' }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="user.status === 'ACTIVE' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'" class="inline-flex px-2 py-1 text-xs font-semibold rounded-full">
                  {{ user.status === 'ACTIVE' ? '正常' : '禁用' }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ formatDate(user.createTime) }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex space-x-2">
                  <button @click="handleEdit(user)" class="text-indigo-600 hover:text-indigo-900">编辑</button>
                  <button @click="handleResetPassword(user)" class="text-yellow-600 hover:text-yellow-900">重置密码</button>
                  <button @click="handleToggleStatus(user)" :class="user.status === 'ACTIVE' ? 'text-red-600 hover:text-red-900' : 'text-green-600 hover:text-green-900'">
                    {{ user.status === 'ACTIVE' ? '禁用' : '启用' }}
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
        <div class="flex-1 flex justify-between sm:hidden">
          <button @click="handlePageChange(currentPage - 1)" :disabled="currentPage <= 1" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
            上一页
          </button>
          <button @click="handlePageChange(currentPage + 1)" :disabled="currentPage >= totalPages" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
            下一页
          </button>
        </div>
        <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
          <div>
            <p class="text-sm text-gray-700">
              共 <span class="font-medium">{{ pagination.total }}</span> 条记录
            </p>
          </div>
          <div>
            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
              <button @click="handlePageChange(currentPage - 1)" :disabled="currentPage <= 1" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                <ChevronLeftIcon class="h-5 w-5" />
              </button>
              <button v-for="page in visiblePages" :key="page" @click="handlePageChange(page)" :class="page === currentPage ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'" class="relative inline-flex items-center px-4 py-2 border text-sm font-medium">
                {{ page }}
              </button>
              <button @click="handlePageChange(currentPage + 1)" :disabled="currentPage >= totalPages" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                <ChevronRightIcon class="h-5 w-5" />
              </button>
            </nav>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mt-6">
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <UserGroupIcon class="h-8 w-8 text-indigo-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">总用户数</p>
            <p class="text-2xl font-semibold text-gray-900">{{ stats.totalUsers }}</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <ShieldCheckIcon class="h-8 w-8 text-green-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">系统管理员</p>
            <p class="text-2xl font-semibold text-gray-900">{{ stats.adminUsers }}</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <UserIcon class="h-8 w-8 text-blue-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">实验室管理员</p>
            <p class="text-2xl font-semibold text-gray-900">{{ stats.labManagers }}</p>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <ExclamationTriangleIcon class="h-8 w-8 text-red-600" />
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-500">禁用用户</p>
            <p class="text-2xl font-semibold text-gray-900">{{ stats.disabledUsers }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建/编辑用户对话框 -->
    <UserForm 
      v-if="showCreateDialog || showEditDialog" 
      :user="editingUser" 
      :is-edit="showEditDialog"
      @close="handleCloseDialog" 
      @save="handleSaveUser" 
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  PlusIcon,
  UserIcon,
  UserGroupIcon,
  ShieldCheckIcon,
  ExclamationTriangleIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
} from '@heroicons/vue/24/outline'
import UserForm from './UserForm.vue'
import request from '@/utils/request'

const router = useRouter()

// 响应式数据
const users = ref([])
const loading = ref(false)
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const editingUser = ref(null)

const searchForm = reactive({
  username: '',
  role: '',
  laboratory: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const stats = reactive({
  totalUsers: 0,
  adminUsers: 0,
  labManagers: 0,
  disabledUsers: 0
})

// 计算属性
const currentPage = computed(() => pagination.currentPage)
const totalPages = computed(() => Math.ceil(pagination.total / pagination.pageSize))
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

// 用户数据将通过API加载

// 方法
const loadUsers = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      username: searchForm.username || undefined,
      role: searchForm.role || undefined,
      laboratoryId: searchForm.laboratory || undefined
    }

    const response = await request.get('/users', { params })
    users.value = response.data.records.map(user => ({
      id: user.id,
      username: user.username,
      realName: user.realName,
      email: user.email,
      role: user.role,
      laboratoryName: user.laboratoryName,
      phone: user.phone,
      status: user.status === 1 ? 'ACTIVE' : 'INACTIVE',
      createTime: user.createTime
    }))
    pagination.total = response.data.total
    
    // 更新统计信息
    updateStats()
    
  } catch (error) {
    console.error('加载用户列表失败:', error)
    showMessage('加载用户列表失败', 'error')
  } finally {
    loading.value = false
  }
}

const updateStats = () => {
  stats.totalUsers = users.value.length
  stats.adminUsers = users.value.filter(u => u.role === 'ADMIN').length
  stats.labManagers = users.value.filter(u => u.role === 'LAB_MANAGER').length
  stats.disabledUsers = users.value.filter(u => u.status === 'INACTIVE').length
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadUsers()
}

const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    role: '',
    laboratory: ''
  })
  pagination.currentPage = 1
  loadUsers()
}

const handlePageChange = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    pagination.currentPage = page
    loadUsers()
  }
}

const handleEdit = (user) => {
  editingUser.value = { ...user }
  showEditDialog.value = true
}

const handleResetPassword = async (user) => {
  if (confirm(`确定要重置用户 "${user.username}" 的密码吗？`)) {
    try {
      await request.post(`/users/${user.id}/reset-password`, null, {
        params: { newPassword: '123456' } // 默认新密码
      })
      showMessage('密码重置成功，新密码已发送到用户邮箱', 'success')
    } catch (error) {
      showMessage('密码重置失败', 'error')
    }
  }
}

const handleToggleStatus = async (user) => {
  const action = user.status === 'ACTIVE' ? '禁用' : '启用'
  if (confirm(`确定要${action}用户 "${user.username}" 吗？`)) {
    try {
      const updateData = {
        ...user,
        status: user.status === 'ACTIVE' ? 0 : 1 // 转换为后端格式
      }
      await request.put(`/users/${user.id}`, updateData)
      user.status = user.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
      showMessage(`用户${action}成功`, 'success')
      updateStats()
    } catch (error) {
      showMessage(`用户${action}失败`, 'error')
    }
  }
}

const handleCloseDialog = () => {
  showCreateDialog.value = false
  showEditDialog.value = false
  editingUser.value = null
}

const handleSaveUser = async (userData) => {
  try {
    // 构建请求数据
    const requestData = {
      username: userData.username,
      realName: userData.realName,
      email: userData.email,
      phone: userData.phone,
      role: userData.role,
      laboratoryId: userData.laboratoryId,
      status: userData.status === 'ACTIVE' ? 1 : 0
    }
    
    if (showEditDialog.value) {
      // 编辑用户
      await request.put(`/users/${userData.id}`, requestData)
      showMessage('用户更新成功', 'success')
    } else {
      // 创建用户
      await request.post('/users', requestData)
      showMessage('用户创建成功', 'success')
    }
    
    handleCloseDialog()
    loadUsers()
    
  } catch (error) {
    console.error('保存用户失败:', error)
    showMessage('保存用户失败', 'error')
  }
}

const getRoleText = (role) => {
  const roleMap = {
    'ADMIN': '系统管理员',
    'LEADER': '上级领导',
    'LAB_MANAGER': '实验室管理员'
  }
  return roleMap[role] || role
}

const getRoleBadgeClass = (role) => {
  const classMap = {
    'ADMIN': 'bg-red-100 text-red-800',
    'LEADER': 'bg-blue-100 text-blue-800',
    'LAB_MANAGER': 'bg-green-100 text-green-800'
  }
  return classMap[role] || 'bg-gray-100 text-gray-800'
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString()
}

// 简单消息提示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

// 生命周期
onMounted(() => {
  loadUsers()
})
</script>